package com.tgy.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;

/***
 * @ClassName: Download
 * @Description: 测试浏览器下载
 * @Auther: 送一一块二向箔
 * @Date: 19:03 2021/12/4
 * @version : V1.0
 */
public class Download extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //要获取的文件路径
        String realpath = "D:/练习项目/javaweb/JavaWeb.md";
        System.out.println("下载路径："+realpath);
        //保存的文件名
        String filename = realpath.substring(realpath.lastIndexOf("/") + 1);

        //设置浏览器的头文件，支持我们下载的文件格式
        resp.setHeader("Content-Disposition","attachment;filename*=utf-8'zh_cn'"+filename);
        //获取下载文件的输入流
        FileInputStream fileInputStream = new FileInputStream(realpath);
        //创建缓冲区
        int len = 0;
        byte[] buffer = new byte[1024];
        ServletOutputStream outputStream = resp.getOutputStream();
        //将FileOutputStream流写入到buff缓冲区
        //使用OutputStream将缓冲区中的数据输出到客户端！
        while ((len = fileInputStream.read(buffer))>0){
            outputStream.write(buffer,0,len);
        }
        fileInputStream.close();
        outputStream.close();


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
